package com.mrd.mrdappstore;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends Activity {

	public static final String	App1packageName	 = "com.example.app1";
	public static final String	App1MainActivity	= "com.example.app1.MainActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewById(R.id.tv1).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// check if app1 openable ;
				// http://wangsheng2008love.blog.163.com/blog/static/78201689201132735042740/
				try {
					Intent intent = new Intent();
					intent.setClassName(App1packageName, App1MainActivity);
					startActivity(intent);
				} catch (Exception e) {
					// e.printStackTrace();
					// 自动下载安装app;http://www.cnblogs.com/Greenwood/archive/2011/03/09/1979268.html
					testInstallApkFromAssets();
				}
				// if not install it from assets
			}
		});
	}

	@Override
	protected void onStart() {
		super.onStart();
		if(testApkIsInstall(App1packageName)) {
			((TextView) findViewById(R.id.tv1)).setText(App1packageName + "[已安装]");
		} else {
			((TextView) findViewById(R.id.tv1)).setText(App1packageName + "[未安装]");
		}
	}

	// check if app1 already install判断Android应用程序是否已安装
	// http://www.open-open.com/lib/view/open1328536302967.html
	public boolean testApkIsInstall(String packageName) {
		PackageInfo packageInfo;

		try {
			packageInfo = this.getPackageManager().getPackageInfo(packageName, 0);

		} catch (NameNotFoundException e) {
			packageInfo = null;
			e.printStackTrace();
		}
		if(packageInfo == null) {
			System.out.println("not installed");
			return false;
		} else {
			System.out.println("is installed");
			return true;
		}
	}

	// 关于android 如何安装 assets文件下的apk
	// http://blog.csdn.net/shen332401890/article/details/8826827
	public void testInstallApkFromAssets() {
		final MainActivity mContext = this;
		if(copyApkFromAssets(this, "app1.apk", Environment.getExternalStorageDirectory()
		        .getAbsolutePath() + "/test.apk")) {
			Builder m = new AlertDialog.Builder(mContext).setIcon(R.drawable.ic_launcher)
			        .setMessage("是否安装？").setIcon(R.drawable.ic_launcher)
			        .setPositiveButton("yes", new DialogInterface.OnClickListener() {
				        @Override
				        public void onClick(DialogInterface dialog,int which) {
					        Intent intent = new Intent(Intent.ACTION_VIEW);
					        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					        intent.setDataAndType(Uri.parse("file://"
					                + Environment.getExternalStorageDirectory().getAbsolutePath()
					                + "/test.apk"), "application/vnd.android.package-archive");
					        mContext.startActivity(intent);
				        }

			        });
			m.show();
		}
	}

	private boolean copyApkFromAssets(Context context,String fileName,String path) {
		boolean copyIsFinish = false;
		try {
			InputStream is = context.getAssets().open(fileName);
			File file = new File(path);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = 0;
			while((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			fos.close();
			is.close();
			copyIsFinish = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return copyIsFinish;
	}

}
